package com.aegis.common.token.utils;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.aegis.common.token.constants.CommonTokenProperties;
import com.aegis.common.token.constants.TokenRedisConstants;
import com.aegis.common.token.model.LoginInfo;
import com.aegis.manage.api.dto.SysUserDTO;
import com.aegis.manage.api.service.UserServiceApi;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author renogo
 *
 * @Version 1.0
 * @Descritube 获取用户登录信息的工具
 */
//@Component
@Deprecated
public class AuthUtil {

    private static CommonTokenProperties commonTokenProperties;

    //    @Autowired
    public void setTokenProperties(CommonTokenProperties commonTokenProperties) {
        this.commonTokenProperties = commonTokenProperties;
    }

    /**
     * 登入
     *
     * @param userId
     * @return
     */
    public static LoginInfo login(String userId, SysUserDTO sysUserDTO) {
        StpUtil.login(userId);
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setTokenInfo(tokenInfo);
        cacheUserInfo(sysUserDTO);
        return loginInfo;
    }


    /**
     * 获取当前登录的用户信息
     *
     * @return
     */
    public static SysUserDTO getLoginUserInfo() {
        return getLoginUserInfo(getUserId());
    }


    /**
     * 获取某个用户的信息，如果有缓存则读缓存，没有则从数据库读取
     *
     * @param userId
     * @return
     */
    public static SysUserDTO getLoginUserInfo(String userId) {
        CommonTokenProperties commonTokenProperties = SpringUtil.getBean(CommonTokenProperties.class);
        SysUserDTO result = null;
        if (commonTokenProperties.isCacheUserInfo()) {
            SaSession sessionByLoginId = StpUtil.getSessionByLoginId(userId);
            result = (SysUserDTO) sessionByLoginId.get(TokenRedisConstants.getUserInfo(userId));
            if (result != null) {
                return result;
            }
        }
        UserServiceApi userServiceApi = SpringUtil.getBean(UserServiceApi.class);
        result = userServiceApi.getUserDetailById(userId);
        if (commonTokenProperties.isCacheUserInfo()) {
            cacheUserInfo(result);
        }
        return result;
    }


    /**
     * 清除当前用户缓存的信息
     */
    public static void clearUserCache() {
        clearUserCache(getUserId());
    }


    /**
     * 清除某个用户缓存的信息
     *
     * @param userId
     */
    public static void clearUserCache(String userId) {
        CommonTokenProperties bean = SpringUtil.getBean(CommonTokenProperties.class);
        //如果有需要缓存信息
        if (!bean.isCacheUserInfo()) {
            return;
        }
        StpUtil.getSessionByLoginId(userId).clear();
    }


    /**
     * 当前用户是否是管理员
     *
     * @return
     */
    public static boolean isAdmin() {
        return isAdmin(AuthUtil.getUserId());
    }


    /**
     * 某个用户是否是管理员
     *
     * @param userId
     * @return
     */
    public static boolean isAdmin(String userId) {
        CommonTokenProperties bean = SpringUtil.getBean(CommonTokenProperties.class);
        if (CollUtil.isEmpty(bean.getAdminRoles())) {
            return false;
        }
        for (String adminRole : bean.getAdminRoles()) {
            if (StpUtil.hasRoleOr(userId, adminRole)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 当前用户登出
     */
    public static void logout() {
        logout(getToken());
    }

    /**
     * 登出
     *
     * @param token
     */
    public static void logout(String token) {
        StpUtil.logoutByTokenValue(token);
    }


    /**
     * 获取当前登录的用户的权限
     *
     * @return
     */
    public static List<String> getPermission() {
        return StpUtil.getPermissionList();
    }

    /**
     * 获取某个用户的权限
     *
     * @param userId
     * @return
     */
    public static List<String> getPermission(String userId) {
        return StpUtil.getPermissionList(userId);
    }


    /**
     * 获取当前用户的角色
     *
     * @return
     */
    public static List<String> getRoles() {
        return StpUtil.getRoleList();
    }

    /**
     * 获取当前用户的角色
     *
     * @return
     */
    public static List<String> getRoles(String userId) {
        return StpUtil.getRoleList(userId);
    }


    /**
     * 获取当前登录的用户id
     *
     * @return
     */
    public static String getUserId() {
        return (String) StpUtil.getLoginId();
    }

    /**
     * 获取当前登录的用户token
     *
     * @return
     */
    public static String getToken() {
        return StpUtil.getTokenValue();
    }


//    /**
//     * 获取当前请求头的 appId
//     *
//     * @return appId 值，如果请求头中没有则返回 null
//     */
//    public static String getAppId() {
//        return getHeader(commonTokenProperties.getHeaderNameAppId());
//    }
//
//    /**
//     * @return
//     */
//    public static String getNonce() {
//        return getHeader(commonTokenProperties.getHeaderNameNonce());
//    }
//
//    /**
//     * @return
//     */
//    public static String getTimestamp() {
//        return getHeader(commonTokenProperties.getHeaderNameTimestamp());
//    }
//
//
//    /**
//     * @return
//     */
//    public static String getSignature() {
//        return getHeader(commonTokenProperties.getHeaderSignature());
//    }
//

//    /**
//     *
//     */
//    public static void checkSign(String body, String signature) {
//        SignatureParams.builder().appId(getAppId())
//                .nonce(getNonce())
//    }

    /**
     * 缓存用户信息
     *
     * @param sysUserDTO
     */
    public static void cacheUserInfo(SysUserDTO sysUserDTO) {
        CommonTokenProperties bean = SpringUtil.getBean(CommonTokenProperties.class);
        if (bean.isCacheUserInfo()) {
            SaSession session = StpUtil.getSession();
            session.set(TokenRedisConstants.getUserInfo(sysUserDTO.getId()), sysUserDTO);
        }
    }


    public static String getHeader(String key) {
        HttpServletRequest request = getHttpServletRequest();
        if (request != null) {
            return request.getHeader(key);
        }
        return null;
    }

    /**
     * 获取当前 HttpServletRequest
     *
     * @return HttpServletRequest 对象
     */
    private static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }


}
